﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Globalization;

namespace Steve.EFDataLayer
{
    [Serializable]
    public class ForeignKeyException : Exception
    {
        public IEnumerable<string> BadKeyValues { get; private set; }

        //TODO: generate message...
        public ForeignKeyException(string[] badKeyValues) : base(GenerateMessage(badKeyValues))
        {
            BadKeyValues = new ReadOnlyCollection<string>(badKeyValues);
        }

        private static string GenerateMessage(string[] badKeyValues)
        {
            return string.Format(CultureInfo.InvariantCulture, "Incorrect foreign key values: '{0}'", string.Join("', '", badKeyValues));
        }

        public ForeignKeyException(string[] badKeyValues, Exception inner) : base(GenerateMessage(badKeyValues), inner)
        {
            BadKeyValues = new ReadOnlyCollection<string>(badKeyValues);
        }

        public ForeignKeyException()
        {
        }

        public ForeignKeyException(string message) : base(message)
        {
        }

        public ForeignKeyException(string message, Exception inner)
            : base(message, inner)
        {
        }

        protected ForeignKeyException(SerializationInfo info, StreamingContext ctx) : base(info, ctx)
        {
            BadKeyValues = (ReadOnlyCollection<string>)info.GetValue("BadKeyValues", typeof(ReadOnlyCollection<string>));
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);

            info.AddValue("BadKeyValues", BadKeyValues);
        }

    }
}
